package com.zb.callback.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zb.callback.entity.HoubanyunConstant;
import com.zb.callback.service.LKaiService;
import com.zb.callback.service.impl.LKaiPushServiceImpl;
import com.zb.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * @Author WEN
 * @Date 2024/8/19 0019
 **/
@Log4j2
@Api(tags = "回调类接口")
@RestController
@RequestMapping("/callback")
public class CallbackController {
    @Resource
    private LKaiService lKaiService;

    @ApiOperation("伙伴云回调接口")
    @PostMapping("/lkaiCallback")
    public Object lkaiCallback(@RequestBody String data) {
        JSONObject obj = JSON.parseObject(data, JSONObject.class);
        log.info("伙伴云回调入参obj：{}", obj);
        // 校验连接
        if (Objects.equals("url_verification", obj.getString("type"))) {
            JSONObject resultObj = new JSONObject();
            resultObj.put("challenge", obj.getString("challenge"));
            log.info("出参resultObj：{}", resultObj);
            return resultObj;
        }
        JSONObject dataObj = JSON.parseObject(obj.getString("data"), JSONObject.class);
        if (null == dataObj) {
            log.info("dataObj为空出参：{}", Result.success());
            return Result.success();
        }
        String tableId = dataObj.getString("table_id");
        // C端工单（安装、维修）
        if (Objects.equals(HoubanyunConstant.C_TABLE_ID, tableId)) {
            lKaiService.saveCOrder(data);
        }
        // B端工单（维修）
        if (Objects.equals(HoubanyunConstant.B_TABLE_ID, tableId)) {
            lKaiService.saveBOrder(data);
        }
        log.info("出参：{}", Result.success());
        return Result.success();
    }

    @GetMapping("/{workId}")
    public Result test(@PathVariable @ApiParam(value = "工单ID", required = true) Long workId) {
        LKaiPushServiceImpl.pushOrderStatus(workId);
        return Result.success();
    }
}
